<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { stringUtils } from 'my-ts-core';
import { reactive, ref, useTemplateRef, watch } from 'vue';
import { useI18n } from 'vue-i18n';

const modelShowDialog = defineModel<boolean>();

const props = defineProps<{
  title?: string;
}>();

const emit = defineEmits<{
  (e: 'confirm', title: string): void;
}>();

const { t } = useI18n();
const localAppFormRef = ref<FormInstance>();
const titleInput = useTemplateRef<HTMLInputElement>('title-input');

const localAppForm = reactive({
  title: props.title,
});

const localAppFormRules = reactive({
  title: [
    {
      validator: (_rule: any, value: any, callback: any) => {
        const errorMessage = stringUtils.isNullOrUndefinedOrEmptyString(value.trim())
          ? t('titleRequired')
          : '';

        errorMessage ? callback(new Error(errorMessage)) : callback();
      },
      trigger: 'change',
    },
  ],
});

watch(
  () => props.title,
  (newValue) => (localAppForm.title = newValue),
);

function confirm(): void {
  localAppFormRef.value?.validate((valid) => {
    if (valid) {
      emit('confirm', localAppForm.title!);
    }
  });
}
</script>

<template>
  <el-dialog
    v-model="modelShowDialog"
    :title="t('setTitle')"
    @keydown.enter="confirm"
    @opened="titleInput?.focus()"
    @closed="localAppFormRef?.resetFields()"
    width="500"
  >
    <el-form ref="localAppFormRef" :model="localAppForm" status-icon :rules="localAppFormRules">
      <el-form-item prop="title">
        <el-input ref="title-input" v-model="localAppForm.title" :placeholder="t('title')" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="modelShowDialog = false">{{ t('cancel') }}</el-button>
        <el-button type="primary" @click="confirm">
          {{ t('confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
